package com.ext.aic.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import com.ext.aic.R;
import com.ext.aic.adapter.binder.ContentItemBinder;
import com.ext.aic.adapter.binder.IndustryEnterpriseListItemBinder;
import com.ext.aic.beans.CompanyItem;
import com.ext.aic.beans.DataItem;
import com.ext.aic.beans.ProductItem;
import com.ext.aic.databinding.ContentCenterItemBinding;
import com.ext.aic.databinding.IndustryEnterpriseListItemViewBinding;
import com.ext.aic.events.ViewTypeBinder;
import com.ext.aic.holder.ContentCenterViewHolder;
import com.ext.aic.holder.IndustryEnterpriseListViewHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Setter;

public class SearchAdapter<T extends DataItem> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    @Setter
    private List<T> items;
    private Map<Class<? extends DataItem>, ViewTypeBinder> binderMap = new HashMap<>();

    public SearchAdapter(Context context) {
        binderMap.put(ProductItem.class, new ContentItemBinder(context));
        binderMap.put(CompanyItem.class, new IndustryEnterpriseListItemBinder(context));
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        if (viewType == 1) {
            View view = inflater.inflate(R.layout.industry_enterprise_list_item_view, parent, false);
            return new IndustryEnterpriseListViewHolder(IndustryEnterpriseListItemViewBinding.bind(view));
        } else {
            View view = inflater.inflate(R.layout.content_center_item, parent, false);
            return new ContentCenterViewHolder(ContentCenterItemBinding.bind(view));
        }
    }

    @Override
    public int getItemViewType(int position) {
        DataItem dataItem = this.items.get(position);
        if (dataItem instanceof ProductItem) {
            return 0;
        } else if (dataItem instanceof CompanyItem) {
            return 1;
        }
        return -1;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        DataItem dataItem = items.get(position);
        ViewTypeBinder binder = binderMap.get(dataItem.getClass());
        if (binder == null) {
            return;
        }
        binder.bind(holder, dataItem, position);
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }
}
